package com.isunland.managesystem.base;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import com.isunland.managesystem.entity.SimpleDialogParams;
import com.isunland.managesystem.utils.MyStringUtil;
import java.io.Serializable;

/**
 * 对象功能:
 * 开发公司: 北京信普达系统工程有限公司
 * 开发人员: wangyanan
 * 创建时间: 2017/5/6 12:16
 */

public class SimpleConfirmDialogFragment extends DialogFragment {
  private static final String EXTRA_PARAMS =
      SimpleConfirmDialogFragment.class.getSimpleName() + ".EXTRA_PARAMS";
  private SimpleDialogParams mParams;

  public static SimpleConfirmDialogFragment newInstance(SimpleDialogParams params) {
    Bundle argsBundle = new Bundle();
    argsBundle.putSerializable(EXTRA_PARAMS, params);
    SimpleConfirmDialogFragment fragment = new SimpleConfirmDialogFragment();
    fragment.setArguments(argsBundle);
    return fragment;
  }

  @Override public void onCreate(Bundle savedInstanceState) {
    Serializable ser = getArguments().getSerializable(EXTRA_PARAMS);
    mParams =
        ser instanceof SimpleDialogParams ? (SimpleDialogParams) ser : new SimpleDialogParams();
    super.onCreate(savedInstanceState);
  }

  @NonNull @Override public Dialog onCreateDialog(Bundle savedInstanceState) {

    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    builder.setTitle(MyStringUtil.isEmpty(mParams.getTitle()) ? "提示" : mParams.getTitle());
    builder.setMessage(mParams.getMessage());
    builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {

      @Override public void onClick(DialogInterface dialog, int which) {
        if (getTargetFragment() == null) return;
        getTargetFragment().onActivityResult(getTargetRequestCode(), Activity.RESULT_OK, null);
      }
    }).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {

      @Override public void onClick(DialogInterface dialog, int which) {

      }
    });
    return builder.create();
  }

  @Override public void onDismiss(DialogInterface dialog) {
    super.onDismiss(dialog);
    if (mParams.isFinishActivityOnDismiss) getActivity().finish();
  }
}
